package com.tsfyun.scm.config.redis;

import com.tsfyun.scm.config.ws.WsConstant;
import com.tsfyun.scm.config.ws.WsHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @CreateDate: Created in 2021/6/29 16:52
 */
@Slf4j
@Component
@AutoConfigureAfter({RedisTemplate.class,WsHandler.class})
public class RedisReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    private WsHandler wsHandler;

    /**
     * 监听redis消息
     */
    @PostConstruct
    public void subscribe( ) {
        wsHandler.setRedisTemplate(redisTemplate);
        RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection();
        //订阅业务通知、ws用户下线通知
        redisConnection.subscribe((message, bytes) -> {
            String channel = new String(message.getChannel());
            String messageBody = new String(message.getBody());
            log.info("监听到来自频道【{}】的消息【{}】",channel,messageBody);
            wsHandler.receiveMessage(channel,messageBody);
        }, new byte[][]{WsConstant.WS_TOPIC.getBytes(StandardCharsets.UTF_8), WsConstant.USER_OFFLINE_TOPIC.getBytes(StandardCharsets.UTF_8)});
    }

}
